import React from 'react'
import {connect} from 'react-redux'
import { Form, message, Switch, Button, Input, InputNumber, Alert } from 'antd';
import {deepFullCopy, messages} from "share/common";
import ResizeTable from 'components/resize-table'
import interfaceService from "containers/financial-account/interface-definition/interface-service";
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class mateRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      record: {},
      saveLoading: false,
      columns: [
        {title: messages('financial-account.key83')/*核算要素编码*/, dataIndex: 'elementCode'},
        {title: messages('financial-account.key84')/*核算要素名称*/, dataIndex: 'elementName'},
        {title: messages('financial-account.key5')/*是否预置*/, width: 96, dataIndex: 'isDefault', render: (value) => value ? messages('components.key378')/*是*/ : messages('components.key377')/*否*/}
      ],
      data: [],
      pagination: {
        total: 0
      },
      page: 0,
      loading: false,
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      selectIds: [],
      showData: []
    }
  }

  componentWillMount() {
    this.getList();
  }

  getList = () => {
    const { page } = this.state;
    const { sceneDefinition } = this.props;
    let temp = {
      sceneDefId: sceneDefinition.id,
      page
    };
    this.setState({loading: true});
    interfaceService.getElementList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, ()=>{
        this.getList();
      })
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({ record: nextProps.editRecord },() => {
      let { record, rowSelection, selectIds, data, showData } = this.state;
      rowSelection.selectedRowKeys = record.sceneElementIdListS || [];
      selectIds = record.sceneElementIdListS || [];
      showData = Object.keys(record).length > 0 ? data.filter(item => selectIds.indexOf(item.id) > -1) : deepFullCopy(data);
      this.setState({ rowSelection, selectIds, showData });
    });
  }

  onSelectChange = (selectedRowKeys) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    let { selectIds } = this.state;
    if(selected){
      selectIds.filter(item => item === record.id).length === 0 && selectIds.push(record.id);
    } else {
      selectIds.map((item,index) => {
        item === record.id && (selectIds[index] = undefined);
      });
      selectIds = selectIds.filter(item => !!item);
    }
    this.setState({selectIds});
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    let { selectIds } = this.state;
    if(selected){
      changeRows.map(item => {
        selectIds.filter(ids => ids === item.id).length === 0 && selectIds.push(item.id);
      })
    } else {
      changeRows.map(item => {
        selectIds.map((ids,index) => {
          if(item.id === ids){
            selectIds[index] = undefined;
          }
        });
      });
      selectIds = selectIds.filter(item => !!item);
    }
    this.setState({selectIds});
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        const { record, selectIds } = this.state;
        const { user, tenant, sceneDefinition } = this.props;
        values.tenantId = tenant.id;
        values.setOfBooksId = sceneDefinition.setOfBooksId;
        values.sceneDefineId = sceneDefinition.id;
        values.sceneElementIdList = selectIds;
        values.createdBy = user.userOID;
        record.id && (values.id = record.id);
        let name = Object.keys(record).length > 0 ? 'updateMate' : 'addMate';
        this.setState({saveLoading: true});
        interfaceService[name](values).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(e => {
          this.setState({saveLoading: false});
          message.error(e.response.data.message);
        })
      }
    })
  };

  handleClear = (e) => {
    e.stopPropagation();
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = [];
    this.setState({ selectIds: [], rowSelection });
  };

  render(){
    const { record, saveLoading, columns, showData, loading, pagination, rowSelection, selectIds } = this.state;
    const { getFieldDecorator } = this.props.form;
    let showText = messages('financial-account.key149',{arg1:pagination.total,arg2:selectIds.length})/*共<span class='normal-dangerously-font'>{arg1}</span>项，已选择<span class='normal-dangerously-font'>{arg2}</span>项*/;
    return(
      <div>
        <Form style={{marginTop:'10px'}}>
          <div>
            <span className='default-color-bg' style={{display: 'inline-block',padding:'0px 6px', color: '#fff', borderRadius: '50%'}}>1</span>
            <span style={{marginLeft: '10px'}}>{messages('common.baseInfo')/*基本信息*/}</span>
          </div>
          <FormItem label={messages('financial-account.key104')/*匹配组编码*/} {...formItemLayout}>
            {getFieldDecorator('groupCode', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.groupCode
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/} disabled={Object.keys(record).length !== 0}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key105')/*匹配组名称*/} {...formItemLayout}>
            {getFieldDecorator('groupName', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.groupName
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key106')/*优先级*/} {...formItemLayout}>
            {getFieldDecorator('priority', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.priority
            })(
              <InputNumber formatter={this.showPriority}
                           disabled={Object.keys(record).length !== 0}
                           placeholder={messages('common.please.input')/*请输入*/}
                           parser={value => value}
                           min={1}/>
            )}
          </FormItem>
          <FormItem label={messages('common.column.status')/*状态*/} {...formItemLayout}>
            {getFieldDecorator('isEnable',{
              initialValue: typeof record.isEnable === "boolean" ? record.isEnable : true,
              valuePropName: 'checked'
            })(
              <Switch/>
            )}
          </FormItem>
          <div>
            <span className='default-color-bg' style={{display: 'inline-block',borderRadius: '50%', padding:'0px 6px', color: '#fff'}}>2</span>
            <span style={{marginLeft: '10px'}}>{messages('financial-account.key107')/*映射字段*/}</span>
            <span style={{marginLeft: '5px',color: '#9f9f9f'}}>{messages('financial-account.key108')/*请选择需要的映射字段：*/}</span>
          </div>
          <Alert style={{margin:'10px 0px'}} type="info" showIcon message={<div>
            <span dangerouslySetInnerHTML={{__html: showText}}/>
            {Object.keys(record).length === 0 && <a style={{marginLeft:'5px'}} onClick={this.handleClear}>{messages('common.clear')/*清空*/}</a>}
          </div>}/>
          <ResizeTable
            columns={columns}
            dataSource={showData}
            loading={loading}
            rowKey={'id'}
            rowSelection={Object.keys(record).length !== 0 ? undefined : rowSelection}
            pagination={pagination}
            bordered/>
        </Form>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    user: state.login.user,
    tenant: state.login.tenant,
    sceneDefinition: state.financialAccount.sceneDefinition
  }
}

const wrappedMateRule = Form.create()(mateRule);
export default connect(mapStateToProps)(wrappedMateRule);
